import javax.servlet.*;
import javax.servlet.http.*;
import java.io.*;
import java.sql.*;
import javax.servlet.annotation.WebServlet;

@WebServlet("/add_book")
public class AddBook extends HttpServlet {
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException {
        response.setHeader("Access-Control-Allow-Origin", "*");
        response.setHeader("Access-Control-Allow-Methods", "*");
        response.setHeader("Access-Control-Allow-Headers", "*");
        response.setContentType("text/plain;charset=UTF-8");

        String number = request.getParameter("number");
        String name = request.getParameter("name");
        String author = request.getParameter("author");
        if (number == null || name == null || author == null) {
            response.getWriter().write("success");
            return;
        }

        String url = "jdbc:mysql://101.37.236.199:3306/linux_exam";
        String user = "root";
        String password = "1qaz@WSX#EDC";

        try {
            Class.forName("com.mysql.cj.jdbc.Driver");
            try (Connection conn = DriverManager.getConnection(url, user, password)) {
                String sql = "INSERT INTO t_book (number, name, author) VALUES (?, ?, ?)";
                PreparedStatement stmt = conn.prepareStatement(sql);
                stmt.setString(1, number);
                stmt.setString(2, name);
                stmt.setString(3, author);
                stmt.executeUpdate();
                response.getWriter().write("success");
            }
        } catch (Exception e) {
            response.getWriter().write("error: " + e.getMessage());
        }
    }
}

